package diandiansong.library.http;

import android.content.Context;

import diandiansong.library.http.okhttputils.callback.Callback;

import java.io.IOException;

import diandiansong.library.utils.AFile;
import diandiansong.library.utils.MD5;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by act on 2016/3/17.
 * CallBack with cache
 */
public abstract class CacheCallBack extends Callback<String> {

    private static final String CACHE_NAME = "SONA_OKHTTP_CACHE";
    private AFile cache;
    private String key;

    public CacheCallBack(Context context) {
        cache = AFile.get(context, CACHE_NAME);
    }

    public abstract void onCache(String cache, int id);

    @Override
    public String parseNetworkResponse(Response response, int id) throws IOException {
        String res = response.body().string();
        if (cache != null && !res.isEmpty()) {
            cache.put(key, res);
        }
        return res;
    }

    /**
     * UI Thread
     *
     * @param request req
     */
    @Override
    public void onBefore(Request request, int id) {
        key = MD5.getMD5(request.toString());
        onCache(cache.getAsString(key), id);
    }
}
